package com.yjt.fresh.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.HttpManager;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener;
import com.yjt.fresh.R;
import com.yjt.fresh.api.ApiLogin;
import com.yjt.fresh.api.ApiOtherLogin;
import com.yjt.fresh.base.BaseSimpleActivity;
import com.yjt.fresh.bean.BeanUserInfo;
import com.yjt.fresh.constant.MyConstants;
import com.yjt.fresh.utils.CommonsToolsHelper;
import com.yjt.fresh.utils.PreferenceManager;
import com.yjt.fresh.widget.CustomToast;
import com.yjt.fresh.widget.CustomToastResult;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * 登录页
 * Created by mcc on 2018/6/5.
 */

public class AtyLogin extends BaseSimpleActivity {
    @BindView(R.id.edtAppAtyLoginPhone)
    EditText mEdtPhone;
    @BindView(R.id.edtAppAtyLoginPassword)
    EditText mEdtPassword;
    @BindView(R.id.btnAppAtyLogin)
    Button mBtnLogin;
    @BindView(R.id.tvAppAtyLoginRegister)
    TextView mTvRegister;
    @BindView(R.id.tvAppAtyLoginForgetPassword)
    TextView mTvForgetPassword;
    @BindView(R.id.ivAppAtyLoginQQ)
    ImageView mIvQQ;
    @BindView(R.id.ivAppAtyLoginWeiXin)
    ImageView mIvWeiXin;
    @BindView(R.id.ivAppAtyLoginWeiBo)
    ImageView mIvWeiBo;
    private boolean isPhoneOk;
    private boolean isPasswordOk;
    private String mOtherLoginType;


    @Override
    protected int getContentView() {
        return R.layout.app_aty_login;
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
    }

    @Override
    protected void initEvent() {
        initClick();
    }

    private void initClick() {
        mEdtPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (count > 0) {
                    isPhoneOk = true;
                    if (isPasswordOk) {
                        mBtnLogin.setClickable(true);
                        mBtnLogin.setBackgroundResource(R.drawable.selector_43b624_00b24f_5);
                    } else {
                        mBtnLogin.setClickable(false);
                        mBtnLogin.setBackgroundResource(R.drawable.shape_e6e6e6_5);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mEdtPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (count > 0) {
                    isPasswordOk = true;
                    if (isPhoneOk) {
                        mBtnLogin.setClickable(true);
                        mBtnLogin.setBackgroundResource(R.drawable.selector_43b624_00b24f_5);
                    } else {
                        mBtnLogin.setClickable(false);
                        mBtnLogin.setBackgroundResource(R.drawable.shape_e6e6e6_5);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mBtnLogin.setClickable(false);
        mBtnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!CommonsToolsHelper.isPhoneNum(mEdtPhone.getText().toString())) {
                    CustomToast.showLong("请输入正确的手机号码");
                } else {
                    toMyLogin();
                }
            }
        });
        mIvQQ.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                qqLogin();
            }
        });

        mIvWeiXin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                weiXinLogin();
            }
        });

        mIvWeiBo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                weiBoLogin();
            }
        });

        mTvRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, AtyRegister.class);
                startActivity(intent);
            }
        });

        mTvForgetPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, AtyForgetPassword.class);
                startActivity(intent);
            }
        });
    }

    private void weiBoLogin() {
        mOtherLoginType = "3";
        UMShareAPI umShareAPI = UMShareAPI.get(mContext);
        umShareAPI.getPlatformInfo(mContext,SHARE_MEDIA.SINA,mUmAuthListener);
    }

    private void weiXinLogin() {
        mOtherLoginType = "1";
        UMShareAPI umShareAPI = UMShareAPI.get(mContext);
        umShareAPI.getPlatformInfo(mContext, SHARE_MEDIA.WEIXIN, mUmAuthListener);
    }

    UMAuthListener mUmAuthListener = new UMAuthListener() {

        private ProgressDialog mProgressDialog;

        @Override
        public void onStart(SHARE_MEDIA share_media) {
            mProgressDialog = new ProgressDialog(mContext);
            mProgressDialog.setMessage("正在登录...");
            mProgressDialog.show();
        }

        @Override
        public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
            if (mProgressDialog != null && mProgressDialog.isShowing()){
                mProgressDialog.dismiss();
            }
            toOtherLogin(map);
        }

        @Override
        public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
            if (mProgressDialog != null && mProgressDialog.isShowing()){
                mProgressDialog.dismiss();
            }
            Toast.makeText(mContext, "失败" + throwable.getMessage(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media, int i) {
            if (mProgressDialog != null && mProgressDialog.isShowing()){
                mProgressDialog.dismiss();
            }
        }
    };

    private void qqLogin() {
        mOtherLoginType = "2";
        UMShareAPI umShareAPI = UMShareAPI.get(mContext);
        umShareAPI.getPlatformInfo(mContext, SHARE_MEDIA.QQ, mUmAuthListener);
    }

    private void toOtherLogin(Map<String, String> map) {
        ApiOtherLogin apiOtherLogin = new ApiOtherLogin(new HttpOnNextListener<BeanUserInfo>() {


            @Override
            public void onNext(BeanUserInfo beanUserInfo) {
                loginSuccess(beanUserInfo);
            }

            @Override
            public void onReLogin() {

            }
        }, mContext, true, false, false);

        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("LOGIN_INFO",map.get("uid"));
        paramMap.put("THIRD_LOGIN_TYPE",mOtherLoginType);
        paramMap.put("NICKNAME",map.get("name"));
        paramMap.put("LOGO_IMG",map.get("iconurl"));
        apiOtherLogin.setMap(paramMap);
        HttpManager.getInstance().doHttpDeal(apiOtherLogin);
    }

    HttpOnNextListener<BeanUserInfo> mLoginListener = new HttpOnNextListener<BeanUserInfo>() {
        @Override
        public void onNext(BeanUserInfo beanUserInfo) {
            loginSuccess(beanUserInfo);
        }

        @Override
        public void failed(String massage) {
            CustomToast.showLong(massage);
        }

        @Override
        public void onReLogin() {
        }
    };

    private void loginSuccess(BeanUserInfo beanUserInfo) {
        CustomToastResult.show("登录成功");
        PreferenceManager.getInstance().setIsLogin(true);
        PreferenceManager.getInstance().setUserInfo(beanUserInfo);
        registerAndSendBroadcast(MyConstants.LOGIN);
        setJpush();
        finish();
    }

    private void setJpush() {

    }

    private void toMyLogin() {
        ApiLogin apiLogin = new ApiLogin(mLoginListener, mContext, true, false, true);
        Map<String, Object> map = new HashMap<>();
        map.put("PHONE", mEdtPhone.getText().toString());
        map.put("LOGIN_PASSWORD", mEdtPassword.getText().toString());
        apiLogin.setMap(map);
        HttpManager.getInstance().doHttpDeal(apiLogin);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    /*
     * (non-Javadoc)
	 *
	 * @see com.gizwits.framework.activity.BaseActivity#didUserLogin(int,
	 * java.lang.String, java.lang.String, java.lang.String)
	 */

    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 01:
                    // 调用 JPush 接口来设置别名。
                    try {
                        JPushInterface.setAliasAndTags(getApplicationContext(),
                                (String) msg.obj, null, mAliasCallback);
                        //JPushInterface.resumePush(getApplicationContext());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    Log.i("CC", "Unhandled msg - " + msg.what);
            }
        }
    };

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    Log.i("CC", logs);
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Log.i("CC", logs);
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    Log.e("CC", logs);
            }
        }
    };
}
